package teacool.service.login;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class CreateUserValidator implements Validator {
	/** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());

	@Override
	public boolean supports(Class arg) {
		return CreateUser.class.equals(arg);
	}

	@Override
	public void validate(Object obj, Errors errors) {
		CreateUser createUser = (CreateUser)obj;
		if( createUser == null ) {
			errors.rejectValue("userName", "error.not-specified", null, "Missing user information.");
		} else {
			logger.info("Validating user creation " + createUser.getUserName() + " for " + createUser.getEmail());
			String userName = createUser.getUserName();
			if( userName == null || userName.trim().length() == 0 ) {
				errors.rejectValue("userName", "error.missing-username", null, "Missing user name.");
			}
			String password = createUser.getPassword();
			if( password == null || password.trim().length() == 0 ) {
				errors.rejectValue("password", "error.missing-password", null, "Missing password.");
			}
			String confirmPwd = createUser.getConfirmPwd();
			if( confirmPwd == null || confirmPwd.trim().length() == 0 ) {
				errors.rejectValue("confirmPwd", "error.missing-confirm-pwd", null, "Missing confirm password.");
			}
			String email = createUser.getEmail();
			if( email == null || email.trim().length() == 0 ) {
				errors.rejectValue("email", "error.missing-email", null, "Missing email address");
			}
			String confirmEmail = createUser.getConfirmEmail();
			if( confirmEmail == null || confirmEmail.trim().length() == 0 ) {
				errors.rejectValue("confirmEmail", "error.missing-confirm-email", null, "Missing confirm email address.");
			}
			
			if( !createUser.getEmail().equals(createUser.getConfirmEmail()) ) {
				errors.rejectValue("confirmEmail", "error.not-match-email", new Object[] {createUser.getEmail()+" & "+createUser.getConfirmEmail()}, "Email doesn't match.");
			}
			if( !createUser.getPassword().equals(createUser.getConfirmPwd()) ) {
				errors.rejectValue("confirmPwd", "error.not-match-pwd", null, "Password doesn't match.");
			}
		}
	}

}
